package com.koko.controller;

import com.github.pagehelper.Page;
import com.koko.constant.FileNameConstant;
import com.koko.feign.AdminFeignService;
import com.koko.game.dto.PublisherDTO;
import com.koko.game.dto.PublisherPageQueryDTO;
import com.koko.game.entity.Publisher;
import com.koko.game.vo.PublisherDetailVO;
import com.koko.game.vo.PublisherVO;
import com.koko.properties.HttpParamsProperties;
import com.koko.properties.HttpPathProperties;
import com.koko.result.PageResult;
import com.koko.result.Result;
import com.koko.service.PublisherService;
import com.koko.utils.HttpUrlUtil;
import com.koko.utils.IOUtil;
import com.koko.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/game")
public class PublisherController {

    @Value("${koko.urlPrefix}")
    private String baseUrl;
    @Value("${koko.path.publisher}")
    private String basePath;

    @Autowired
    private PublisherService publisherService;

    @Autowired
    private AdminFeignService adminFeignService;

    /**
     * 分页查询
     *
     * @param publisherPageQueryDTO
     * @return
     */
    @GetMapping("/admin/publisher/page")
    public PageResult<Publisher> adminManagementCategoryList(PublisherPageQueryDTO publisherPageQueryDTO) {
        Page<Publisher> page = publisherService.pageQuery(publisherPageQueryDTO);
        for (Publisher publisher : page.getResult()) {
            publisher.setIcon(
                    HttpUrlUtil.imageRequestUrlEncapsulate(
                            baseUrl + HttpPathProperties.GAME_PUBLISHER_ICON_DOWNLOAD,
                            HttpParamsProperties.GAME_PUBLISHER_ICON_ID + publisher.getId().toString(),
                            HttpParamsProperties.GAME_PUBLISHER_ICON_NAME + publisher.getIcon()
                    )
            );
        }
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 新增游戏分类
     *
     * @param publisherInfo
     * @param imageFile
     * @return
     */
    @PostMapping("/admin/publisher")
    public Result<String> addCategory(
            @RequestParam("publisherInfo") String publisherInfo,
            @RequestParam(value = "image", required = false) MultipartFile imageFile) {
        PublisherDTO publisherDTO = JSONUtil.parseObject(publisherInfo, PublisherDTO.class);
        publisherService.save(publisherDTO, imageFile);
        return Result.success();
    }

    /**
     * 批量删除游戏分类
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/admin/publisher")
    public Result<String> deleteCategory(@RequestBody List<Long> ids) {
        publisherService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改分类信息
     *
     * @param publisherInfo
     * @param imageFile
     * @return
     */
    @PutMapping("/admin/publisher")
    public Result<String> updateCategory(
            @RequestParam("publisherInfo") String publisherInfo,
            @RequestParam(value = "image", required = false) MultipartFile imageFile) {
        // 1. 将json字符串转化为对象
        PublisherDTO publisherDTO = JSONUtil.parseObject(publisherInfo, PublisherDTO.class);
        publisherService.update(publisherDTO, imageFile);
        return Result.success();
    }

    /**
     * 根据id查询游戏分类详细信息
     *
     * @param id
     * @return
     */
    // TODO 发行商详细页需要显示相关游戏
    @GetMapping("/admin/publisher/{id}")
    public Result<PublisherDetailVO> getById(@PathVariable Long id) {
        // 1. 查询数据
        Publisher publisher = publisherService.getById(id);
        // 2. 封装数据
        PublisherDetailVO publisherDetailVO = new PublisherDetailVO();
        // 2.1 封装基本数据
        BeanUtils.copyProperties(publisher, publisherDetailVO, "createUserId", "updateUserId");
        // 2.2 封装图片url数据
        publisherDetailVO.setIcon(
                HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_PUBLISHER_ICON_DOWNLOAD,
                        HttpParamsProperties.GAME_PUBLISHER_ICON_ID + publisher.getId().toString(),
                        HttpParamsProperties.GAME_PUBLISHER_ICON_NAME + publisher.getIcon()
                )
        );
        // 2.3 封装发行商介绍文本
        try {
            publisherDetailVO.setIntroduction(IOUtil.readFileToString(
                    basePath +
                            publisher.getId() + "/" +
                            publisher.getIntroduction()));
        } catch (IOException e) {
            // 没找到，传递空字符串
            publisherDetailVO.setIntroduction(null);
        }
        // 2.4.1 通过feign获取创建者和修改者姓名
        Result<String> createAdminResult = adminFeignService.getAdminDetail(publisher.getCreateUserId());
        Result<String> updateAdminResult = adminFeignService.getAdminDetail(publisher.getUpdateUserId());
        // 2.4.2 封装创建者和修改者姓名数据
        publisherDetailVO.setCreateUser(createAdminResult.getData());
        publisherDetailVO.setUpdateUser(updateAdminResult.getData());
        return Result.success(publisherDetailVO);
    }

    @GetMapping("/publishers")
    public Result<List<PublisherVO>> getAllPublisher(@RequestParam(required = false) String name) {
        List<PublisherVO> list = publisherService.getAllPublishers(name);
        return Result.success(list);
    }

    @GetMapping("/fromnews/publisher/{id}")
    public Result<Publisher> getPublisherInNewsById(@PathVariable Long id) {
        // 1. 查询数据
        Publisher publisher = publisherService.getById(id);
        publisher.setCreateTime(null);
        publisher.setUpdateTime(null);
        // 2 封装图片url数据
        publisher.setIcon(
                HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_PUBLISHER_ICON_DOWNLOAD,
                        HttpParamsProperties.GAME_PUBLISHER_ICON_ID + publisher.getId().toString(),
                        HttpParamsProperties.GAME_PUBLISHER_ICON_NAME + publisher.getIcon()
                )
        );
        return Result.success(publisher);
    }

    @GetMapping("/fromnews/publisher/page")
    public PageResult<Publisher> getPublisherPageInNews(PublisherPageQueryDTO publisherPageQueryDTO) {
        Page<Publisher> page = publisherService.pageQuery(publisherPageQueryDTO);
        for (Publisher publisher : page.getResult()) {
            publisher.setIcon(
                    HttpUrlUtil.imageRequestUrlEncapsulate(
                            baseUrl + HttpPathProperties.GAME_PUBLISHER_ICON_DOWNLOAD,
                            HttpParamsProperties.GAME_PUBLISHER_ICON_ID + publisher.getId().toString(),
                            HttpParamsProperties.GAME_PUBLISHER_ICON_NAME + publisher.getIcon()
                    )
            );
        }
        List<Publisher> list = page.getResult().stream().map((item) -> {
            item.setCreateTime(null);
            item.setUpdateTime(null);
            return item;
        }).collect(Collectors.toList());
        return new PageResult<>(page.getTotal(), list);
    }
}
